﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using GroceryList.Model.Repositories;
using Xunit;

namespace GroceryList.Test
{
    public class ReflectonTest
    {
        [Fact]
        public void PuedoSaberLosInterfacesDeTipoRepositorio()
        {
            var tipos = Assembly.GetAssembly(typeof(ProductoRepository)).GetTypes();
            var tipoRepo = tipos.Where(tipo => tipo.FindInterfaces(RepositoryTypeFilter, "Repository").Count() > 0).ToList();
            Assert.NotNull(tipoRepo.Where(tp => tp.ToString().Contains("ProductoRepository")).FirstOrDefault());
            Assert.NotNull(tipoRepo.Where(tp => tp.ToString().Contains("ListaCompraRepository")).FirstOrDefault());
            Assert.Null(tipoRepo.Where(tp => tp.ToString().Contains("BaseRepository")).FirstOrDefault());
        }

        [Fact]
        public void PuedoSaberLosTiposDeTipoRepositorio()
        {
            var tipos = Assembly.GetAssembly(typeof(ProductoRepository)).GetTypes();
            var tipoRepo = tipos.Where(tipo => tipo.FindInterfaces(RepositoryTypeFilter, "Repository").Count() > 0).ToList();
            var tipoIRepo = new List<Type>();
            foreach (var tipo in tipoRepo)
            {
                tipoIRepo.AddRange(tipo.FindInterfaces(RepositoryTypeFilter, "Repository"));
            }


            Assert.NotNull(tipoIRepo.Where(tp => tp.ToString().Contains("IProductoRepository")).FirstOrDefault());
            Assert.NotNull(tipoIRepo.Where(tp => tp.ToString().Contains("IListaCompraRepository")).FirstOrDefault());
        }

        private static bool RepositoryTypeFilter(Type m, object filtercriteria)
        {
            return m.ToString().EndsWith(filtercriteria.ToString());
        }

        [Fact]
        public void PuedoAccederAlDirectorioDeLosFicherosDeScriptUsandoRutasRelativasDesdeElAssemblyEnEjecucion()
        {   
            var strFilePath = Directory.GetCurrentDirectory();
            strFilePath = Directory.GetParent(strFilePath).ToString();
            strFilePath = Directory.GetParent(strFilePath).ToString();
            strFilePath = Directory.GetParent(strFilePath).ToString();
            strFilePath = Directory.GetParent(strFilePath).ToString();
            var scriptToTestPath = String.Format("{0}{1}{2}", strFilePath, Path.DirectorySeparatorChar, "ScriptToTest");

            Assert.True(Directory.Exists(scriptToTestPath));
            Assert.True
            (
                Directory.GetFiles(String.Format("{0}{1}", scriptToTestPath, Path.DirectorySeparatorChar),"*.sql").Count()>0
            );

        }
    }
}
